package com.guo.www.pkcs12;

import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V3CertificateGenerator;

import javax.security.auth.x500.X500Principal;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

public class Pkcs12 {

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	public void genRootCA(String path,String fileName, String passWord, String issuer) {
		try {
			KeyStore keyStore = PkcsTools.getStore();
			KeyPair keyPair = PkcsTools.getKeyPair(1024);
			X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
			certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
			certGen.setIssuerDN(new X500Principal(issuer));
			certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
			certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
			certGen.setSubjectDN(new X500Principal(issuer));
			certGen.setPublicKey(keyPair.getPublic());
			certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

			certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

			certGen.addExtension(X509Extensions.KeyUsage, true,
					new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

			certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
					new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

			certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
					new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

			X509Certificate cert = certGen.generateX509Certificate(keyPair.getPrivate(), "BC");

			System.out.println(cert.toString());

			keyStore.setKeyEntry("CA", keyPair.getPrivate(), passWord.toCharArray(), new Certificate[] { cert });
			FileOutputStream outStream = new FileOutputStream(path+"\\"+fileName+".pfx");
			keyStore.store(outStream, passWord.toCharArray());
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


}
